我正在尝试创建一个如下所示的布局:
输入到 EditText 中并动态解析的单词并在 AdapterView 中显示为其自己的 TextView。如果 EditText 中未输入任何内容,则 AdapterView 也将为空。如果一行无法容纳太多单词,则会将其添加到下一行。最后,您会得到一堵充满适配器的 TextView 的“砖墙”。
我很难找到有关如何实现这种外观的指南。我想在 XML 中定义尽可能多的内容。我正在设想这样的事情:
<!-- Activity.xml -->
<RelativeLayout>
<TextView>
<EditText>
<AdapterView>
</RelativeLayout>
但是现有的适配器(ListView、GridView)都不适合我在这里尝试做的事情。
谁能给我一些学习的例子吗?
最佳答案
如果您尝试创建一个具有自定义外观的列表,那么您是对的,基本 ListView 适配器是不够的。您需要创建自己的。
您可以通过创建一个扩展 ArrayAdapter 的类和一个使用上面的定义预定义的 xml View 来完成此操作:
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
public class ExampleAdapter extends ArrayAdapter<Object> {
private int resource;
private LinearLayout layoutItem;
public ExampleAdapter(Context context, int _resource, ArrayList<Object> itemList) {
super(context, _resource, itemList);
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
try{
//****************************************************
// instantiate the layout
//****************************************************
if(convertView == null){
layoutItem = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater vi;
vi = (LayoutInflater)getContext().getSystemService(inflater);
vi.inflate(resource, layoutItem, true);
}else{
layoutItem = (LinearLayout) convertView;
}
//****************************************************
// bind the layout controls
//****************************************************
TextView myTextView = (TextView)layoutItem.findViewById(R.id.myTextView);
// extend to other view controls...
//****************************************************
// use the item object to get information about it
//****************************************************
int Id = item.get_id();
// do whatever else you need to the display of the layout
return layoutItem;
}catch(Exception e){
e.printStackTrace();
}
}
现在,您无需调用基本适配器,而是调用自定义适配器,传入需要与布局资源一起显示的项目列表。
关于java - 自定义适配器 View (带图片),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17891451/