Android TableLayout не отображает строки - PullRequest
1 голос
/ 31 марта 2012

У меня возникают проблемы с отображением моих строк в TableLayout.

Я распространяю строки программно с помощью этого метода:

private void buildStatesTable() {
    Log.d(SelectStatesPanel.class.getCanonicalName(), "Entering Build States Table");
    ArrayList<String> states = new ArrayList<String>();
    Random rand = new Random();

    for(int i = 0; i < 10; i++){
        if(i < goodStates.length){
            states.add(goodStates[i]);
        }else{
            states.add(badStates[rand.nextInt(badStates.length)]);
        }
    }

    Collections.shuffle(states);

    TableLayout tl = (TableLayout) findViewById(R.id.statesTable);
    final int NUM_PER_ROW = 2;

    for(int i = 0; i < (states.size() / NUM_PER_ROW); i++){
        TableRow tr = new TableRow(getContext());
        tr.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));

        for(int j = 0; j < NUM_PER_ROW && (i*NUM_PER_ROW + j) < states.size(); j++){
            TextView lblState = new TextView(getContext());
            lblState.setText(states.get(i*NUM_PER_ROW + j));
            lblState.setTextColor(Color.BLACK);
            lblState.setLayoutParams(new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT));
            lblState.setClickable(true);
            lblState.setOnClickListener(this);
            tr.addView(lblState);

            //Log.d(SelectStatesPanel.class.getCanonicalName(), "Adding State: " + states.get(i*NUM_PER_ROW + j));
            Log.d(SelectStatesPanel.class.getCanonicalName(), "\t\t\t (" + i + ", " + j + ")");
        }

        // Add the TableRow to the TableLayout
        tl.addView(tr);
        Log.d(SelectStatesPanel.class.getCanonicalName(), "Adding Row");
    }
}

И это мой XML (макет таблицывнизу):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"        
        android:layout_margin="5dip"

        android:text="Good choice! There's hope for you yet."
        android:textSize="16dip"
        android:textStyle="bold"
        android:gravity="center"
        />

    <TextView
        android:id="@+id/txtLex"

        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"        
        android:layout_margin="5dip"

        android:text="Lexington"
        android:textSize="14dip"
        android:gravity="center"
        />
    <TextView
        android:id="@+id/txtTampa"

        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"        
        android:layout_margin="5dip"

        android:text="Tampa"
        android:textSize="14dip"
        android:gravity="center"
        />
    <TextView
        android:id="@+id/txtSacramento"

        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"        
        android:layout_margin="5dip"

        android:text="Sacramento"
        android:textSize="14dip"
        android:gravity="center"
        />
    <TextView
        android:id="@+id/txtHiltonhead"

        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"        
        android:layout_margin="5dip"

        android:text="Hiltonhead"
        android:textSize="14dip"
        android:gravity="center"
        />

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"        
        android:layout_margin="5dip"

        android:gravity="center"
        android:src="@drawable/usa"
        />
    <TableLayout 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"        
        android:layout_margin="5dip"
        android:id="@+id/statesTable"
        android:stretchColumns="0,1">        
    </TableLayout>


</LinearLayout>

Почему мой макет таблицы не отображает содержимое?

Ответы [ 3 ]

0 голосов
/ 31 марта 2012

Закомментируйте весь код строки и замените его строкой просмотра текста с двумя строками. Это работает? Тогда проблема может быть в массиве, из которого вы строите свои представления строк. С наилучшими пожеланиями.

0 голосов
/ 01 апреля 2012

Я обнаружил проблему самостоятельно.

Проблема была в следующем:

        lblState.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));

Задание TableRow.LayoutParams решило проблему.

0 голосов
/ 31 марта 2012

Я не вижу конкретно, что идет не так в вашем коде, но вот аналогичная реализация в моем собственном коде:

public class EconFragment extends Fragment {


    private TableLayout questionContainer;
    static int pos = 0;
    private String[] titles = {"The first title ", "hallo1","hallo2", "hallo3",
            "hallo4", "hallo5","hallo6", "hallo7","hallo8", "hallo9"};

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d("Econ", "onCreateView");

        return inflater.inflate(R.layout.econfragment, container, false);
    }

    public void onResume() {
        super.onResume();


        LayoutInflater inflater = (LayoutInflater) getActivity().
        getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        questionContainer = (TableLayout) getActivity().findViewById(R.id.questionContainer);



        //these lines are my first attempt to try and get the questions to repopulate after returning
        //from pressing back - as of yet, they don't repopulate the screen:
        //View econFragment = inflater.inflate(R.layout.econfragment, null);
        //container.addView(econFragment);

        int leftMargin=5;
        int topMargin=5;
        int rightMargin=5;
        int bottomMargin=5;
        while (pos < 10) {
        View question = inflater.inflate(R.layout.question, null);
        question.setId(pos);
        TextView title = (TextView) question.findViewById(R.id.questionTextView);
        title.setText(titles[pos]);
        Button charts = (Button) question.findViewById(R.id.chartsButton);
        charts.setId(pos);
        charts.setOnClickListener(chartsListener);
        TableRow tr = (TableRow) question;
        TableLayout.LayoutParams trParams = new TableLayout.LayoutParams(
                TableLayout.LayoutParams.MATCH_PARENT,
                TableLayout.LayoutParams.WRAP_CONTENT);
        trParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
        tr.setLayoutParams(trParams);

        questionContainer.addView(tr);
        pos++;
        }
        Log.d("Econ", "onResume");
    }

И источник вопросаContainer, econfragment.xml:

<?xml version="1.0" encoding="utf-8"?>

   <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/scrollView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <TableLayout 
            android:id="@+id/questionContainer"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        </TableLayout>
     </ScrollView>

Как видите, объект Question.class создается как объект View во фрагменте EconFragment. Объект вопрос используется для поиска ViewById для каждой необходимой части.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...