Динамическая таблица - вставка содержимого текстового представления в существующую таблицу - PullRequest
0 голосов
/ 29 января 2019

Я создаю свое первое приложение для Android и хочу использовать Dynamic Tablerow в своем приложении.В моем MainFragment.java есть OnClickListener для добавления текста.Я использую Log.d, чтобы проверить, работает ли он или нет.Я проверил это работает.Но текст не добавляется в Tablerow;его идентификатор mealRow.Я хочу добавить TextView в существующий Tablerow.Пожалуйста, проверьте это и ответьте мне.Спасибо.

Я попробовал новый Tablerow.Но это также не удалось.Я имею в виду новый TextView в новом Tablerow в существующем TableLayout.

MainFragment.java

public static MainFragment newInstance() {
    return new MainFragment();
}

@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final View view = inflater.inflate(R.layout.main_fragment, container, false);

    Response.Listener<String> responseListener;
    responseListener = new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            String mealList = response;
            Log.d(TAG, mealList+"");
            //TextView meal = (TextView) getView().findViewById(R.id.meal1);
            //meal.setText(mealList);
        }
    };
    Log.d(TAG, "Meal queued!");
    MealRequest mealRequest = new MealRequest(countryCode, schulCode, insttNm, schulCrseScCode,
            schMmealScCode, schYmd, responseListener);
    RequestQueue queue = Volley.newRequestQueue(getActivity());
    queue.add(mealRequest);

    Button create = (Button) view.findViewById(R.id.Create);

    create.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "button Clicked!");
            TableRow mealRow = (TableRow) view.findViewById(R.id.mealRow);
            ViewGroup.LayoutParams textParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            TextView meals = new TextView(getActivity());
            meals.setText("new");
            meals.setLayoutParams(textParams);
            meals.setGravity(Gravity.CENTER);
            meals.setTextColor(Color.parseColor("#000000"));
            meals.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
            mealRow.addView(meals);
        }
    });

    return view;
}

MainActivity.java

private final static String TAG = MainActivity.class.getName();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.add(R.id.fragment_container, MainFragment.newInstance()).commit();
    navigationView.setNavigationItemSelectedListener(this);

}

**--------------------------------cut--------------------------**

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_home) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, MainFragment.newInstance()).commit();
    } else if (id == R.id.nav_calendar) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, Calendar.newInstance()).commit();
    } else if (id == R.id.nav_timetable) {

    } else if (id == R.id.nav_homework) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

main_fragment.xml

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Today's meal"
    android:textColor="#000000"
    android:textSize="20sp"/>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TableLayout
        android:id="@+id/mealTable"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:stretchColumns="*">

        <TableRow
            android:id="@+id/mealRow"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/meal1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="1dp"
                android:layout_marginBottom="1dp"
                android:gravity="center"
                android:text="1"
                android:textColor="#000000"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/meal2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="1dp"
                android:layout_marginBottom="1dp"
                android:gravity="center"
                android:text="2"
                android:textColor="#000000"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/meal3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="1dp"
                android:layout_marginBottom="1dp"
                android:gravity="center"
                android:text="3"
                android:textColor="#000000"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/meal4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="1dp"
                android:layout_marginBottom="1dp"
                android:gravity="center"
                android:text="4"
                android:textColor="#000000"
                android:textSize="20sp" />

        </TableRow>
    </TableLayout>
</RelativeLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:orientation="horizontal">

    <Button
        android:id="@+id/Create"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Make Text!" />
</LinearLayout>

Это мое ожидание:

  1. Нажмите кнопку «Создать»

  2. добавлен новый TextView в foodRow (Tablerow)

, но на самом деле вывод «Ничего не произошло».

1 Ответ

0 голосов
/ 31 января 2019

Вы должны использовать TableRow.LayoutParams, чем ViewGroup.LayoutParams.

Это потому, что TextView переходит в TableRow.

Если TextView переходит в RelativeLayout, вы должны использовать RelativeLayout.LayoutParams.

...