0

Я работал над простым Android-приложением, которое вычисляет индекс массы тела человека. У меня есть все функции, работающие, но позиционирование стрелки в нужном месте в цветовой полосе, соответствующей размеру экрана пользователя, - это то, что я застрял. Я работаю, устанавливая значения X и Y стрелки ImageView, но, очевидно, место стрелки изменяется, когда я тестирую свое приложение в разных размерах экрана, даже если im покрывает значение dp для пикселей. Как я могу поместить стрелку ImageView так, чтобы она оставалась одинаковой в разных размерах экрана?Как разместить ImageView в одном месте в разных размерах экрана?

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
app:layout_behavior="@string/appbar_scrolling_view_behavior" 
tools:context="coding.guillermo.bmiapp.MainActivity2" 
tools:showIn="@layout/activity_main2" 
android:clickable="false" 
android:background="#ffffff" 
android:id="@+id/relativeLayout"> 


<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="BMI" 
    android:id="@+id/bmiText" 
    android:textSize="25dp" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true" /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="21.24" 
    android:id="@+id/bmiResult" 
    android:textSize="30dp" 
    android:layout_below="@+id/bmiText" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="22dp" /> 



<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/bmiCategory" 
    android:textSize="25dp" 
    android:text="Normal weight" 
    android:layout_marginTop="22dp" 
    android:layout_below="@+id/bmiResult" 
    android:layout_centerHorizontal="true" /> 


<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Save result" 
    android:id="@+id/saveButton" 
    android:backgroundTint="@color/toolBarColor" 
    android:textColor="#ffffff" 
    android:layout_marginBottom="20dp" 
    android:layout_alignParentBottom="true" 
    android:layout_alignParentEnd="true" /> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="BMI Log" 
    android:id="@+id/trackerButton2" 
    android:backgroundTint="@color/toolBarColor" 
    android:textColor="#ffffff" 
    android:layout_alignTop="@+id/saveButton" /> 

<ImageView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/imageView" 
    android:background="@drawable/bmibar" 
    android:layout_marginTop="36dp" 
    android:layout_below="@+id/bmiCategory" /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Underweight &lt;18.50 " 
    android:id="@+id/underweightText" 
    android:textSize="22sp" 
    android:layout_below="@+id/imageView" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="33dp" /> 
<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Normal 18.5 - 24.99" 
    android:id="@+id/normalText" 
    android:textSize="22sp" 
    android:paddingTop="5dp" 
    android:layout_below="@+id/underweightText" 
    android:layout_alignStart="@+id/underweightText" /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Overweight >=25.00" 
    android:id="@+id/overweightText" 
    android:layout_below="@+id/normalText" 
    android:textSize="22sp" 
    android:paddingTop="5dp" 
    android:layout_alignStart="@+id/normalText" /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Obese >=30.00" 
    android:id="@+id/obeseText" 
    android:textSize="22sp" 
    android:paddingTop="5dp" 
    android:layout_below="@+id/overweightText" 
    android:layout_alignStart="@+id/overweightText" /> 

public class MainActivity2 extends AppCompatActivity { 
TextView resultText,bmiLabel,underWeightText,normalText,overweightText,obeseText; 
RelativeLayout.LayoutParams params; 
Button saveButton,trackerButton; 
Result result; 
EditText userName; 
DBhandler dbHandler; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main2); 
    // TextViews 
    resultText = (TextView) findViewById(R.id.bmiResult); 
    bmiLabel = (TextView) findViewById(R.id.bmiCategory); 
    underWeightText = (TextView) findViewById(R.id.underweightText); 
    normalText = (TextView) findViewById(R.id.normalText); 
    overweightText = (TextView) findViewById(R.id.overweightText); 
    obeseText = (TextView) findViewById(R.id.obeseText); 
    // Button 
    saveButton = (Button) findViewById(R.id.saveButton); 
    trackerButton = (Button) findViewById(R.id.trackerButton2); 
    // Getting User object from the previous activity 
    result = (Result) getIntent().getParcelableExtra("result"); 
    // Database 
    dbHandler = new DBhandler(this); 

    // Displaying the arrow in the corresponding place 
    ImageView arrow = new ImageView(this); 
    params = new RelativeLayout.LayoutParams(80,80); 
    arrow.setImageResource(R.drawable.arrow2); 
    RelativeLayout rl = (RelativeLayout) findViewById(R.id.relativeLayout); 

    // the display of the arrow is different when tested in device's with different screen sizes 
    int dpValue = 0; 
    int dpValue2 = 166; 
    float d = getApplicationContext().getResources().getDisplayMetrics().density; 
    int margin = (int)(dpValue * d); 
    int margin2 = (int) (dpValue2 * d); 

    arrow.setX(margin); 
    arrow.setY(margin2); 
    rl.addView(arrow); 

    // BMI diplay 
    resultText.setText(Double.toString(result.getBMI())); 
    bmiLabel.setText(result.getBmiCategory()); 
    // BMI category bold display 
    bmiCategoryBold(result.getBMI()); 

    // Saving result to internal storage for later retrieval 
    saveButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      View view = (LayoutInflater.from(MainActivity2.this)).inflate(R.layout.alert_content,null); 
      AlertDialog.Builder alertBuilder = new AlertDialog.Builder(MainActivity2.this); 
      alertBuilder.setView(view); 
      userName = (EditText) view.findViewById(R.id.nameInput); 
      SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); 
      String date = dateFormat.format(new Date()); 
      result.setDate(date); 
      alertBuilder.setCancelable(true).setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 
      result.setName(userName.getText().toString()); 
      // adding result to the SQLite database 
      dbHandler.addResult(result); 
      Toast toast = Toast.makeText(getApplicationContext(),"result saved",Toast.LENGTH_SHORT); 
      toast.show(); 

       } 
      }); 
      AlertDialog dialog = alertBuilder.create(); 
      dialog.show(); 
      Button nButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE); 
      nButton.setBackgroundColor(getResources().getColor(R.color.toolBarColor)); 
      nButton.setTextColor(Color.WHITE); 

     } 
    }); 

    trackerButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Intent intent = new Intent(getApplicationContext(),MainActivity3.class); 
      startActivity(intent); 
     } 
    }); 

} 


public void bmiCategoryBold(double bmi){ 
    if(bmi < 18.50){ 
     underWeightText.setTypeface(null, Typeface.BOLD); 
    } 
    else if(bmi <= 24.99){ 
     normalText.setTypeface(null,Typeface.BOLD); 
    } 
    else if(bmi<=29.99){ 
     overweightText.setTypeface(null,Typeface.BOLD); 
    } 
    else{ 
     obeseText.setTypeface(null,Typeface.BOLD); 
    } 
} 

} 

Первый ПИК приложение работает на 1080 пикселей на 1920 пикселей экрана, а второй является 1440 пикселей на 2560 пикселей экрана

first pic

second pic

+0

Установите флажок [Поддержка нескольких экранов] (https://developer.android.com/guide/practices/screens_support.html), официальное руководство по проектированию макетов для разных размеров экрана. –

ответ

0

Добавить Linearlayout в качестве подпара а также его атрибут ориентации и силы тяжести, вы можете легко получить дизайн более оптимизированным образом и подходящим для вечного экрана. здесь я использовал RelativeLayout как Parent и LinearLayout в качестве дочернего элемента childview.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical"> 


    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:gravity="center" 
     android:orientation="vertical" 
     android:padding="10dp"> 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:gravity="center" 
      android:orientation="vertical"> 

      <TextView 
       android:id="@+id/bmiText" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="BMI" 
       android:textSize="25dp" /> 

      <TextView 
       android:id="@+id/bmiResult" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:padding="5dp" 
       android:text="21.24" 
       android:textSize="30dp" /> 


      <TextView 
       android:id="@+id/bmiCategory" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="Normal weight" 
       android:textSize="25dp" /> 


     </LinearLayout> 

     <ImageView 
      android:id="@+id/imageView" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:background="@mipmap/ic_launcher" /> 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:gravity="center" 
      android:orientation="vertical" 
      android:padding="5dp"> 

      <TextView 
       android:id="@+id/underweightText" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:padding="10dp" 
       android:text="Underweight &lt;18.50 " 
       android:textSize="22sp" /> 

      <TextView 
       android:id="@+id/normalText" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:padding="10dp" 
       android:text="Normal 18.5 - 24.99" 
       android:textSize="22sp" /> 

      <TextView 
       android:id="@+id/overweightText" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:padding="10dp" 
       android:text="Overweight >=25.00" 
       android:textSize="22sp" /> 

      <TextView 
       android:id="@+id/obeseText" 
       android:layout_width="wrap_content" 
       android:padding="10dp" 
       android:layout_height="wrap_content" 
       android:text="Obese >=30.00" 
       android:textSize="22sp" /> 


     </LinearLayout> 


     <LinearLayout 
      android:layout_width="match_parent" 
      android:orientation="horizontal" 
      android:layout_height="wrap_content"> 

      <LinearLayout 
       android:layout_width="match_parent" 
       android:gravity="left" 
       android:layout_height="wrap_content"> 

       <Button 
        android:id="@+id/trackerButton2" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:backgroundTint="#000000" 
        android:text="BMI Log" 
        android:gravity="center" 
        android:textColor="#ffffff" /> 

       <LinearLayout 
        android:layout_width="match_parent" 
        android:gravity="right" 
        android:layout_height="wrap_content"> 
        <Button 
         android:id="@+id/saveButton" 
         android:layout_width="wrap_content" 
         android:layout_height="wrap_content" 
         android:gravity="center" 
         android:backgroundTint="#000000" 
         android:text="Save result" 
         android:textColor="#ffffff" /> 


       </LinearLayout> 


      </LinearLayout> 

     </LinearLayout> 
    </LinearLayout> 
</RelativeLayout> 

Старайтесь избегать слишком большого края сверху и снизу.

+0

спасибо за решение – GuillermoS