[英]How to call method from a java class (not an activity, no layout) to an activity?
[英]How to call method from activity to change layout?
我怎样才能调用changeTitle()
的方法VideoLayout
内部onItemClick
活动的事件?
我正在尝试找出更改列表项内容的最佳实践。
做v.changeTitle((VideoModel) videoAdapter.getItem(position).title);
(我认为这是我想到的第一个解决方案)抛出“未定义的方法”错误。
有困难吗?
我不会解释该代码,因为我认为这是自我解释:
活动:
public class MainActivity extends BaseActivity {
public void setVideosList()
{
videoAdapter = new VideoAdapter(this, videoItems);
listView.setAdapter(videoAdapter);
listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> av, View v, int position, long arg3) {
}
});
new getVideosTask().execute();
}
}
video.xml(我刚刚粘贴了它的开始。这种布局是列表项中的内容)
<com.company.project.VideoLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="15dp"
android:paddingTop="15dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:descendantFocusability="blocksDescendants"
android:id="@+id/wrapper">
VideoAdapter.java:
public class VideoAdapter extends BaseAdapter{
@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
VideoLayout view;
if (convertView == null) {
view = (VideoLayout) LayoutInflater.from(context).inflate(R.layout.video, parent, false);
}else{
view = (VideoLayout) convertView;
}
VideoModel item = (VideoModel) getItem(position);
if (item != null) {
view.prepare(item);
}
return view;
}
}
VideoModel.java:
class VideoModel {
public String title;
public String videoUrl;
public String imageUrl;
}
VideoLayout.java:
class VideoLayout extends LinearLayout{
public Context context;
public MyImageView imageView;
public MyVideoView videoView;
public TextView titleView;
public VideoLayout(Context context) {
super(context);
this.context = context;
}
public VideoLayout (Context context, AttributeSet attrs) {
super(context, attrs);
}
public VideoLayout (Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
protected void onFinishInflate()
{
super.onFinishInflate();
imageView = (MyImageView) findViewById(R.id.placeholder);
videoView = (MyVideoView) findViewById(R.id.video);
titleView = (TextView) findViewById(R.id.title);
}
public void changeTitle(String text){
titleView.setText(text);
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
View wrapper = view.findViewById(R.id.wrapper);
if(wrapper != null && wrapper instanceof VideoLayout) {
wrapper.changeTitle("title");
}
}
解决了!
我已经简化了它(基于@thinear的答案):
@Override
public void onItemClick(AdapterView<?> av, View v, int position,
long id) {
VideoLayout wrapper = (VideoLayout) v.findViewById(R.id.wrapper);
wrapper.changeTitle("title");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.