На мобильном устройстве кнопка выглядит не так, как при просмотре макета студии android - PullRequest
0 голосов
/ 29 мая 2020

Я определил три кнопки, используя один и тот же файл фона "find_button. xml". Кнопка "начать активность сервера" (id = "start_button") почему-то игнорирует файл "find_button. xml". Я не могу найти ни одной ошибки ..

Просмотр макета в android studio:

Layout view in android studio

Просмотр макета на мобильном устройстве:

enter image description here

xml Файл макета:

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:background="#1A91C6"
    tools:context=".ServerInitial">


    <Button
        android:id="@+id/start_button"

        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginStart="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginBottom="24dp"
        android:background="@drawable/find_button"
        android:backgroundTint="#DCB235"
        android:onClick="startServerActivity"
        android:text="@string/start_server_button"
        android:textColor="#FFFFFF"
        android:textSize="25sp"
        app:layout_constraintBottom_toTopOf="@+id/close_button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <ListView
        android:id="@+id/peers_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginStart="24dp"

        android:layout_marginLeft="24dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginBottom="24dp"
        android:cacheColorHint="?android:attr/colorMultiSelectHighlight"
        android:visibility="visible"
        app:layout_constraintBottom_toTopOf="@+id/start_button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/find_button">


    </ListView>

    <Button
        android:id="@+id/find_button"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginStart="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        android:background="@drawable/find_button"
        android:backgroundTint="#DCB235"
        android:drawableLeft="@drawable/ic_search_black_72dp"
        android:gravity="left|center_vertical"
        android:onClick="sucheGeräte"
        android:text="@string/suchen_button"
        android:textColor="#FFFFFF"
        android:textSize="25sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/close_button"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginStart="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginBottom="32dp"
        android:background="@drawable/find_button"
        android:backgroundTint="#E3931D"
        android:onClick="closeConnection"
        android:text="@string/close_connection"
        android:textColor="#FFFFFF"
        android:textSize="25sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

фоновый файл с возможностью рисования «find_button. xml»

    <?xml vers`enter code here`ion="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:radius="20dp" />
</shape>

Новая информация: Я установил новую и понял, что, пока появлялись запросы на разрешение, кнопка выглядела так, как должна была выглядеть. После подтверждения запросов на разрешение кнопка изменилась на прежний вид.

enter image description here

Я использую довольно приятную процедуру «имеет разрешения» в onCreate для проверки разрешений, возможно, ошибка где-то там.

public class ServerInitial extends AppCompatActivity implements WifiP2pManager.PeerListListener, WifiP2pManager.ConnectionInfoListener {

public static final String TAG = MainActivity.class.getSimpleName();
public WifiP2pManager manager;
public WifiP2pManager.Channel channel2;
public BroadcastReceiver receiver;
public IntentFilter intentFilter;
private List<WifiP2pDevice> peers_list = new ArrayList<>();
private ListView peerslist;
private int count = 0;
private String[] devicenames;
public WifiP2pDevice device;
public Button start;


private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {

        android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
        android.Manifest.permission.CAMERA,
        android.Manifest.permission.ACCESS_FINE_LOCATION
};

public static boolean hasPermissions(Context context, String... permissions) {
    if (context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
}


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    if (!hasPermissions(this, PERMISSIONS))
        ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);


    manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);


    assert manager != null;
    channel2 = manager.initialize(this, getMainLooper(), null);
    receiver = new P2PBroadcastReceiver(manager, channel2, ServerInitial.this, ServerInitial.this,
            ServerInitial.this);
    intentFilter = new IntentFilter();
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
    setContentView(R.layout.activity_server_initial);

    start = findViewById(R.id.start_button);
    // Check if recreating a previously destroyed instance.
    if (savedInstanceState != null) {
        //Restore value of members from saved state.
        devicenames = savedInstanceState.getStringArray("list");
        fillListe();
    } else {

        devicenames = null;

        // Initialize members with default values for a new instance.
        // ...
    }


    manager.discoverPeers(channel2, new WifiP2pManager.ActionListener() {
        @Override
        public void onSuccess() {
            System.out.println("Da draussen ist was los .......");
            //ergebnisSuche.setText("Da ist was los...");

        }

        @Override
        public void onFailure(int reason) {
            System.out.println("Da draussen ist nix los .......");
            //ergebnisSuche.setText("Da ist nix los...");

        }
    });


}

Ответы [ 2 ]

0 голосов
/ 30 мая 2020

Я нашел решение. Позже я внесу некоторые изменения в кнопку «запустить сервер» в своем коде. Кажется, это заставляет кнопку игнорировать фоновый рисунок. Я назначил в своем коде возможность рисования с помощью start.setBackground (...), и теперь он работает. (См. Код ниже)

 @Override
public void onConnectionInfoAvailable(WifiP2pInfo info) {
    if (info.groupFormed) {

        if (info.isGroupOwner) {


            //Intent intent1 = new Intent(this, ServerActivity.class);
            //startActivity(intent1);
            start.setBackgroundColor(getResources().getColor(R.color.lightGreen));
            start.setText("Connected !! Push Button to start..");
            start.setBackground(getResources().getDrawable(R.drawable.find_button));
            start.setTextColor(Color.GREEN);
            start.setTypeface(Typeface.DEFAULT_BOLD);
            start.setEnabled(true);
        } else {
0 голосов
/ 29 мая 2020

В вашем коде нет ничего плохого. Попробуйте переустановить приложение один раз, и оно должно работать нормально. если он не пытается аннулировать кеши и перезапускать опцию в вашей студии android, а затем установить / запустить ваше приложение. Я пробовал ваш тот же код на своем физическом устройстве, а также в эмуляторе, и вот результаты. Физическое устройство

Emulator

...