Как добавить один элемент с четырьмя опциями в ListView?

1

Я создаю базу данных и таблицу "TABLE_NAME", которые содержат один вопрос и 4 варианта.
Мой вопрос заключается в том, как показать этот вопрос с опцией в listview.
Я ищу много статей, но не могу найти подходящий метод для добавления 5 предметов за раз.
Пожалуйста, предоставьте мне ссылку или код.
Я пытаюсь использовать расширяемый список. но он не показывает вопрос и показывается только
один вариант из 4 варианта.
Вот мой пример кода.

public class ObjectiveExamActivity extends ExpandableListActivity {

@SuppressWarnings("unchecked")
public void onCreate(Bundle savedInstanceState) {
    try{
         super.onCreate(savedInstanceState);
         setContentView(R.layout.displayobjectiveque);
         Intent intent=getIntent();
         setResult(RESULT_OK, intent);

    SimpleExpandableListAdapter expListAdapter =
        new SimpleExpandableListAdapter(
                this,
                createGroupList(),              
                R.layout.group_row,             
                new String[] { "Group Item" },  
                new int[] { R.id.row_name },    
                createChildList(),              
                R.layout.child_row,             
                new String[] {"Sub Item"},      
                new int[] { R.id.grp_child}     
            );
        setListAdapter( expListAdapter );       

    }catch(Exception e){
        System.out.println("Error+++ " + e.getMessage());
    }
}

@SuppressWarnings("unchecked")
private List createGroupList() {
      ArrayList result = new ArrayList();
    final MySQLiteHelper m=new MySQLiteHelper(getBaseContext());
    final List<ObjectiveWiseQuestion> LocWiseProfile= m.getAllObjectiveQuestion();       

    for (final ObjectiveWiseQuestion cn : LocWiseProfile)
    {       
        HashMap m1=new HashMap();
        m1.put("Item","Option:"+cn.getQuestion());
        result.add(m1);         
    }
     /* for( int i = 0 ; i < 15 ; ++i ) { // 15 groups........
        HashMap m = new HashMap();
        m.put( "Group Item","Group Item " + i ); // the key and it value.
        result.add( m );
      }*/
      return (List)result;
}

@SuppressWarnings("unchecked")
private List createChildList()
{
    final MySQLiteHelper m=new MySQLiteHelper(getBaseContext());
    final List<ObjectiveWiseQuestion> LocWiseProfile= m.getAllObjectiveQuestion();  
    ArrayList result = new ArrayList();
    for (final ObjectiveWiseQuestion cn : LocWiseProfile)
    { // this -15 is the number of groups(Here it fifteen)
      /* each group need each HashMap-Here for each group we have 3 subgroups */
      ArrayList secList = new ArrayList(); 
      for( int n = 0 ; n < 4 ; n++ ) 
      {
        HashMap child = new HashMap();
        child.put( "Sub Item", "Sub Item " + m.getAllObjectiveQuestion() );
        child.put(cn.getOptionA(), cn.getOptionB());
        child.put("Option C", cn.getOptionC());
        child.put("Option D", cn.getOptionD());
        secList.add( child );
      }
     result.add( secList );
    }        
    return result;
}

public void  onContentChanged  () {
    System.out.println("onContentChanged");
    super.onContentChanged();         
}
/* This function is called on each child click */
public boolean onChildClick( ExpandableListView parent, View v, int groupPosition,int childPosition,long id) {
    System.out.println("Inside onChildClick at groupPosition = " + groupPosition +" Child clicked at position " + childPosition);
    return true;
}

/* This function is called on expansion of the group */
public void  onGroupExpand  (int groupPosition) {
    try{
         System.out.println("Group exapanding Listener => groupPosition = " + groupPosition);
    }catch(Exception e){
        System.out.println(" groupPosition Errrr +++ " + e.getMessage());
    }
}  

}

Заранее спасибо.

  • 2
    Попробуй expandibleListView ...
Теги:
listview

2 ответа

2

Расширяемый ListView может быть вашей работой.

1

Я действительно не уверен, что вам нужно, но попробуйте это приложение:

расположение:

<!-- list_item_multiselect.xml -->
<?xml version="1.0" encoding="utf-8"?>
<CheckBox xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/variant"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Variant" />
<!-- main.xml -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

Мероприятия:

public class Option_listActivity extends Activity {

    private static final String TITLE = "var_title"; 

    private ListView mListView; 

    private Map<String, String> createVariant(String text) 
    {
        Map<String, String> res = new HashMap<String, String>();
        res.put(TITLE, text);
        return res;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mListView = (ListView)findViewById(R.id.listView1);

        List<Map<String, String>> variants = new ArrayList<Map<String, String>>();
        variants.add(createVariant("Option 1"));
        variants.add(createVariant("Option 2"));
        variants.add(createVariant("Option 3"));
        variants.add(createVariant("Option 4"));

        TextView header = new TextView(this);
        header.setText("Choose variant:");
        mListView.addHeaderView(header);

        Button footer = new Button(this);
        footer.setText("Check");
        footer.setOnClickListener(okayButtonListener);
        mListView.addFooterView(footer);

        mListView.setAdapter(new SimpleAdapter(this, variants, R.layout.list_item_multiselect, new String[] {TITLE}, new int[] {R.id.variant}));


    }

    private OnClickListener okayButtonListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            int count = mListView.getCount() - mListView.getHeaderViewsCount() - mListView.getFooterViewsCount();
            String result = "";
            for (int i = 0; i < count; i++) 
            {
                CheckBox cb = (CheckBox)mListView.getChildAt(i + 1);
                if (cb.isChecked()) 
                {
                    result += "Option " + (i + 1) + " checked\n";
                }
            }
            Toast.makeText(Option_listActivity.this, result, Toast.LENGTH_LONG).show();
        }

    };
}

Если вам нужно выбрать только один вариант, вам нужно сделать обновление

Ещё вопросы

Сообщество Overcoder
Наверх
Меню