android screen orientation

2019-01-09 09:25发布

I tried getOrientation() to get the orientation value but it always returns 0!

8条回答
祖国的老花朵
2楼-- · 2019-01-09 09:46

You should use:

getResources().getConfiguration().orientation

It can be one of ORIENTATION_LANDSCAPE, ORIENTATION_PORTRAIT.

http://developer.android.com/reference/android/content/res/Configuration.html#orientation

查看更多
3楼-- · 2019-01-09 09:48

I think you need to create two different layouts and inflate different layouts on different orientation. I am giving you a sample code which is working fine for me. "context" you can pass from your activity in case of custom adapter. If you are using custom adapter then you can try this code:

@Override
public View getView(final int position,
                    View convertView,
                    ViewGroup parent)
{
    View rowView = convertView;
    ViewHolder holder = null;
    int i = context.getResources().getConfiguration().orientation;

    if (rowView == null) {
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (i == Configuration.ORIENTATION_PORTRAIT) {
            rowView = inflater.inflate(R.layout.protrait_layout, null, false);
        } else {
            rowView = inflater.inflate(R.layout.landscape_layout, null, false);
        }

        holder = new ViewHolder();
        holder.button = (Button) rowView.findViewById(R.id.button1);
        rowView.setTag(holder);

    } else {
        holder = (ViewHolder) rowView.getTag();
    }
    return rowView;
}

other wise you can directly set two different layouts in your code

    int i = context.getResources().getConfiguration().orientation;

        if (i == Configuration.ORIENTATION_PORTRAIT) {
                    ArrayAdapter<String> adt = new ArrayAdapter<String>(getApplicationContext(), R.layout.protrait_layout, name);
        } else {
                    ArrayAdapter<String> adt = new ArrayAdapter<String>(getApplicationContext(), R.layout.landscape_layout, name);
        }
查看更多
登录 后发表回答