将imageView参数更改为所有卡片

时间:2016-08-03 13:36:23

标签: android android-layout screen-rotation

我使用RecyclerView并在其Adapter每个列表项中都有CardView内的图片和一些文字。

问题:我想以编程方式更改每个ImageView的权重。

这是在屏幕旋转上运行的代码:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        SquareImageView imgView = (SquareImageView) findViewById(R.id.thumbnail);
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) imgView.getLayoutParams();
        lp.weight = 0.1f;
    }
}

代码只在一张卡上运行,而不是在所有卡上运行。

编辑: 我的适配器代码如果需要:

// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(Context context, RecyclerView recyclerView, LinkedList<CardData> myDataset)
{
    mContext = context;
    mRecyclerView = recyclerView;
    mDataset = myDataset;
}

// Create new views (invoked by the layout manager)
@Override
public ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType)
{
    // create a new view
    final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_card_view, parent, false);
    final ViewHolder viewHolder = new ViewHolder(view);

    view.setOnTouchListener(new View.OnTouchListener() {
        private GestureDetector gestureDetector = new GestureDetector(parent.getContext(), new GestureDetector.SimpleOnGestureListener() {
            Not Relevant
        });

        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            return gestureDetector.onTouchEvent(event);
        }});

    return viewHolder;
}

// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder holder, int position)
{
    CardData currentCard = mDataset.get(position);

    holder.mHeadline.setText(currentCard.mHeadline);

}

1 个答案:

答案 0 :(得分:0)

这不是更改RecyclerViewonConfigurationChanged的列表项中的布局项的实际方法

您需要修改适配器代码和check if the orientation is tablet or not

因此,在适配器中,您需要在onBindViewHolder

中设置类似的布局权重
if(tablet){
    lp.weight = 0.1f;
} else {
    lp.weight = 1; // Whatever
}

现在在onConfigurationChanged,您只需要重置适配器。

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Reset your adapter here.
    myAdapter.resetAdapter();
}