有人可以告诉我如何将百分比方法(Multiple screen resolution,如Muhammad Babar所建议的)应用于片段因为我使用的是Babar提到的方法,但是我在模拟器中运行时遇到错误不幸的是,申请已经停止。我不明白我做错了什么。
这是我的代码:
的xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:id="@+id/contents"
android:layout_width="320px"
android:layout_height="456px" >
<Button
android:id="@+id/Button01"
android:layout_width="60px"
android:layout_height="30px"
android:layout_margin="1dp"
android:background="#3D3D3D"
android:textColor="#FCFCFC"
android:textSize="25px" />
<EditText
android:id="@+id/edittext"
android:layout_width="320px"
android:layout_height="235px"
android:ems="10"
android:gravity="top"
android:inputType="textMultiLine"
android:textSize="20px" />
<Button
android:id="@+id/Button02"
android:layout_width="60px"
android:layout_height="30px"
android:layout_margin="1dp"
android:background="#3D3D3D"
android:textColor="#FCFCFC"
android:textSize="25px" />
/>
</RelativeLayout>
我的片段类:
import android.app.ActionBar.LayoutParams;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
public class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View fragmentView = inflater.inflate(
R.layout.my_fragment, container, false);
// Inflate the layout for this fragment
//
super.onCreate(savedInstanceState);
RelativeLayout mLayoutContents = (RelativeLayout) fragmentView
.findViewById(R.id.contents);
final ViewTreeObserver mLayoutObserver = mLayoutContents.getViewTreeObserver();
mLayoutObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout()
{
RelativeLayout mLayoutContents = (RelativeLayout) fragmentView
.findViewById(R.id.contents);
DisplayMetrics metrics = getResources().getDisplayMetrics();
int deviceWidth = metrics.widthPixels;
int deviceHeight = metrics.heightPixels;
float widthInPercentage = ( (float) 320 / 320 ) * 100;
float heightInPercentage = ( (float) 456 / 480 ) * 100;
int mLayoutWidth = (int) ( (widthInPercentage * deviceWidth) / 100 );
int mLayoutHeight = (int) ( (heightInPercentage * deviceHeight) / 100 );
LayoutParams layoutParams = new LayoutParams(mLayoutWidth, mLayoutHeight);
mLayoutContents.setLayoutParams(layoutParams);
}
});
return fragmentView;
}}